package cn.itcast.service;

import cn.itcast.config.AliyunSMSConfig;
import com.aliyuncs.CommonRequest;
import com.aliyuncs.CommonResponse;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.http.MethodType;
import com.aliyuncs.profile.DefaultProfile;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.RandomUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.time.Duration;

/**
 * 短信业务
 *  1.sendSms(String mobile)
 *      发送短息业务
 *  2.sendCheckCode(String phone)
 *      -> 根据手机号码检查redis服务器中是否已经存在验证码(1个手机号码只能5分钟收到一条验证码)
 *      -> redis服务器中如果不存在则调用1发送验证码并存入redis服务器中(设置有效期5分钟)
 *
 */
@Service
@Slf4j
public class SMSService {

    @Autowired
    private  AliyunSMSConfig aliyunSMSConfig;

    @Autowired
    private  RedisTemplate<String,String> redisTemplate;

    /**
     * 发送短信验证码 并存到redis服务器中
     *
     * @param phone
     * @return
     */
    public  String sendSms(String phone) {
        DefaultProfile profile = DefaultProfile.getProfile(aliyunSMSConfig.getRegionId(),
                aliyunSMSConfig.getAccessKeyId(), aliyunSMSConfig.getAccessKeySecret());
        IAcsClient client = new DefaultAcsClient(profile);

        String code = RandomUtils.nextInt(100000, 999999) + "";

        CommonRequest request = new CommonRequest();
        request.setSysMethod(MethodType.POST);
        request.setSysDomain(aliyunSMSConfig.getDomain());
        request.setSysVersion("2017-05-25");
        request.setSysAction("SendSms");
        request.putQueryParameter("RegionId", aliyunSMSConfig.getRegionId());
        request.putQueryParameter("PhoneNumbers", phone); //目标手机号
        request.putQueryParameter("SignName", aliyunSMSConfig.getSignName()); //签名名称
        request.putQueryParameter("TemplateCode", aliyunSMSConfig.getTemplateCode()); //短信模板code
        request.putQueryParameter("TemplateParam", "{\"code\":\"" + code + "\"}");//模板中变量替换
        try {
            CommonResponse response = client.getCommonResponse(request);
            String data = response.getData();
            if (StringUtils.contains(data, "\"Message\":\"OK\"")) {
                //根据手机号码生产redis缓存key
                String redisKey = "REDIS_KEY_" + phone;
                //保存到redis中并设置有效期5分钟
                redisTemplate.opsForValue().set(redisKey, code, Duration.ofMinutes(5));
                return code;
            }
            log.info("发送短信验证码失败~ data = " + data);
        } catch (Exception e) {
            log.error("发送短信验证码失败~ mobile = " + phone, e);
        }
        return null;
    }

    /**
     * 验证手机号码跟验证码
     * @param phone
     * @param validateCode
     * @return
     */
    public  boolean checkCode(String phone, String validateCode) {
        //根据输入的手机号码生产redis中的key
        String redisKey = "REDIS_KEY_" + phone;
        //从redis中取出验证码
        String redisCode = redisTemplate.opsForValue().get(redisKey);
        //校验验证码
        if (!StringUtils.equals(validateCode,redisCode)) {
            //验证码不正确
            return false;
        }
        return true;
    }
}
